package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.ThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinIOFileStorageService storageService;

    @Autowired(required = false)
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //参数校验
        if (multipartFile == null) {
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断用户是否登录
        WmUser user = (WmUser) ThreadLocalUtils.get();
        if (user == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            //把图片存入到MinIO中
            //分配随机唯一的文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //取出文件后缀名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = uuid + suffixName;

            String url = storageService.uploadImgFile("", filename, multipartFile.getInputStream());

            WmMaterial material = new WmMaterial();
            material.setUserId(user.getId());
            material.setUrl(url);
            material.setType((short) 0);
            material.setIsCollection((short) 0);
            material.setCreatedTime(new Date());
            save(material);

            // 返回存储后的素材信息
            return ResponseResult.okResult(material);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }

    }

    /**
     * 素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findList(WmMaterialDto dto) {
        //参数判断
        dto.checkParam();

        //判断用户是否登录
        WmUser user = (WmUser) ThreadLocalUtils.get();
        if (user == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        Short isCollection = dto.getIsCollection();
        if (isCollection == null) isCollection = 0;

        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId()).eq("is_collection",isCollection);

        queryWrapper.orderByDesc("created_time");

        page = wmMaterialMapper.selectPage(page,queryWrapper);
        PageResponseResult pageResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResult.setData(page.getRecords());
        pageResult.setCode(200);
        return pageResult;
    }
}
